import { Form, Modal, AutoComplete, Input, message } from 'antd';
import React, { useState } from 'react';
import { HTTP_STATUS } from "@/generic/ConfigParams";

const FormItem = Form.Item;

const FormItems = props => {

    const { modalCfgs, form} = props;
    const formItems = modalCfgs.formItems;
    
    const createItems = () => {

        const items = [];
        formItems instanceof Array
        && formItems.forEach((item, i) => {
            items.push(
                <FormItem 
                    key={i}
                    labelCol={item.labelCol || modalCfgs.defaultLabelCol}
                    wrapperCol={item.wrapperCol || modalCfgs.defaultWrapperCol}
                    label={item.label}
                >
                    {form.getFieldDecorator(item.name, {
                        ...item.options
                    })(item.html)}
                </FormItem>
            )
        })

        return items;
    }

    return <> {createItems()} </>
}

const ModalForm = props => {

    const { modalVisible, form, dispatch, modalCfgs = {} } = props;
    const okText = modalCfgs.okText || '提交'
    const cancelText = modalCfgs.cancelText || '取消'

    const okHandle = () => {
        form.validateFields( async (err, fieldsValue) => {
            if (err) return;
            const { type, payload, method } = modalCfgs.okAction;
            const hide = message.loading('正在添加');
            const response = await dispatch({
                type,
                method,
                payload: { ...payload, fields: fieldsValue, }
            })
            hide();
            if (response && response.ok) {
                form.resetFields();
                message.success('添加成功');
                dispatch({ type: 'manager/updateModalVisible', payload: false });
            }
            else {
                console.log("==>> response", response)
                const error_msg = response && response.status ? HTTP_STATUS[response.status] : "";
                message.error(`添加失败！${error_msg}`);
            }
        });
    };

    return (
        <>
            <Modal
                destroyOnClose
                title={modalCfgs.title}
                visible={modalVisible}
                onOk={okHandle}
                onCancel={() => modalCfgs.onCancel(dispatch)}
                okText={okText}
                cancelText={cancelText}
            >
                <FormItems 
                    modalCfgs={modalCfgs}
                    form={form}
                />
            </Modal>
        </>
    );
}

export default ModalForm;